<template>
  <div class="app-container">
    <el-card>
      <title-line title="基本信息" />
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="模板类型：" prop="type" required>
              <el-radio-group v-model="formData.type">
                <el-radio
                  v-for="(item, index) in SHORT_LETTER_TYPE"
                  :key="index"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="模板code：" prop="code">
              <el-input
                v-model="formData.code"
                placeholder="请输入阿里云模板code"
                @blur="codeBlur"
              />
            </el-form-item>
            <el-form-item label="模板参数：" prop="paramList">
              <template v-if="paramList.length">
                <el-input
                  v-for="(item, index) in paramList"
                  :key="index"
                  disabled
                  :value="item"
                  class="mb-10"
                  placeholder="输入模板code，自动填充模板参数"
                />
              </template>
              <el-input v-else disabled placeholder="输入模板code，自动填充模板参数" />
            </el-form-item>
            <el-form-item label="模板内容：" prop="content">
              <el-input
                v-model.trim="formData.content"
                type="textarea"
                placeholder="请输入模板code，自动填充内容"
                :autosize="{ minRows: 6, maxRows: 8 }"
                disabled
              />
              <p class="alert-color">模板内容必须经过第三方短信服务平台备案通过才可以发送成功</p>
              <p class="alert-color">教育、医疗、酒类、引导加微信容易被运营商屏蔽，请谨慎发送</p>
            </el-form-item>
            <el-form-item label="场景说明：" prop="scene">
              <el-input
                v-model.trim="formData.scene"
                type="textarea"
                placeholder="请输入场景的具体说明，以便更好的管理短信模板"
                :autosize="{ minRows: 6, maxRows: 8 }"
              />
            </el-form-item>
            <el-form-item label="排序值：" prop="sort">
              <el-input v-model="formData.sort" placeholder="请输入排序值" clearable />
              <p class="alert-color">数值越小越靠前</p>
            </el-form-item>
            <el-form-item label="是否启用：" prop="isEnable" required>
              <el-radio-group v-model="formData.isEnable">
                <el-radio
                  v-for="(item, index) in SHORT_LETTER_STATUS"
                  :key="index"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="text-align: center">
          <el-button @click="resetForm"> 取消 </el-button>
          <el-button type="primary" :loading="loading" @click="submitForm"> 确定 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import _ from 'lodash'
import { SHORT_LETTER_TYPE, SHORT_LETTER_STATUS } from '@/enum/message'
export default {
  name: 'AddMessageTemplate',
  components: {},
  props: [],
  data() {
    return {
      loading: false,
      formData: {
        code: '',
        paramList: [],
        type: 2,
        content: '',
        scene: '',
        sort: '',
        isEnable: false
      },
      paramList: [],
      rules: {
        code: [
          {
            required: true,
            message: '请输入模板code',
            trigger: 'blur'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入模板code，自动填充内容',
            trigger: 'blur'
          }
        ],
        scene: [
          {
            max: 70,
            message: '字数在70字以内',
            trigger: 'blur'
          }
        ],
        sort: [
          {
            required: true,
            message: '请输入排序值',
            trigger: 'blur'
          },
          {
            pattern: /^[1-9]\d{0,3}$/,
            message: '请输入1-9999'
          }
        ]
      }
    }
  },
  computed: {
    SHORT_LETTER_TYPE() {
      return SHORT_LETTER_TYPE.filter(item => item.value)
    },
    SHORT_LETTER_STATUS() {
      return SHORT_LETTER_STATUS
    }
  },
  created() {
    this.getDetail()
  },
  methods: {
    // 获取参数内容
    async codeBlur() {
      if (!this.formData.code) {
        this.paramList = []
        this.formData.paramList = []
        return
      }
      const {
        data: { content }
      } = await this.$http.message.templateApi.getTemplateContent(this.formData.code)
      this.formData.content = content
      let isParams = content.includes('$')
      this.paramList =
        isParams &&
        content.match(/\{.*?\}/g).map(item => {
          item = item.replace(/{/, '')
          item = item.replace(/}/, '')
          return item
        })
      this.formData.paramList = this.paramList.length ? this.paramList.join(',') : ''
    },
    // 新增
    add: _.debounce(async function () {
      const params = {
        coverType: 0,
        ...this.formData
      }
      const { status, msg } = await this.$http.message.templateApi.add(params)
      if (status === 200) {
        this.$message.success('添加成功')
        this.$router.back(-1)
      } else {
        this.$message.error(msg)
      }
    }, 200),
    // type: 'update'获取详情
    async getDetail() {
      const { id, type } = this.$route.query
      if (!type) return
      const { data } = await this.$http.message.templateApi.getDetail(id)
      for (const key in this.formData) {
        this.formData[key] = data[key]
      }
      this.codeBlur()
    },
    // 编辑
    updated: _.debounce(async function () {
      const { id } = this.$route.query
      const { status, msg } = await this.$http.message.templateApi.update({
        ...this.formData,
        id
      })
      if (status === 200) {
        this.$message.success('编辑成功')
        this.$router.back(-1)
      } else {
        this.$message.error(msg)
      }
    }, 200),
    submitForm() {
      const { type } = this.$route.query
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        this.loading = true
        if (type === 'update') {
          this.updated()
        } else {
          this.add()
        }
        this.loading = false
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$router.back(-1)
    }
  }
}
</script>
<style lang="scss" scoped>
.alert-color {
  color: $hw-text-color-title;
  font-size: 12px;
  line-height: 20px;
  padding: 5px 0;
}
</style>
